package com.gree.scmservice.dao;

import com.gree.common.entity.TablePageData;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Sql;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class LogInfoDao {

    @Autowired
    private Dao dao;

    public int getLoginLogCount(String comp, String filter){
        Sql sql = Sqls.create("select count(*) as nums from sys_logininfor login,$smbse01 sb1,$smcom09 sc09 " +
                " where login.login_name = sb1.usid and login.comp = sc09.comp " + filter);
        sql.setVar("smbse01","smbse01"+comp).setVar("smcom09","smcom09");
        sql.setCallback(Sqls.callback.entity());
        sql.setEntity(dao.getEntity(Record.class));
        dao.execute(sql);
        Record countRecord=(Record) sql.getResult();
        int count= countRecord.getInt("nums");
        return count;
    }

    public TablePageData<Record> displayLoginLog(String comp, String filter, int count, int page, int pageSize){
        Sql sql = Sqls.create("select sb1.nama,login.*,sc09.dsca from sys_logininfor login,$smbse01 sb1,$smcom09 sc09" +
                " where login.login_name = sb1.usid and login.comp = sc09.comp " + filter);
        Pager pager = dao.createPager(page,pageSize);
        pager.setRecordCount(count);
        sql.setVar("smbse01","smbse01"+comp).setVar("smcom09","smcom09");
        sql.setPager(pager);
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(Record.class));
        List<Record> dataList=dao.execute(sql).getList(Record.class);
        return new TablePageData(dataList, pager);
    }

    public Record getLoginLogByNameLatest(String loginName){
        Sql sql = Sqls.create("select * from (select * from sys_logininfor where login_name = @loginName and status = '0' and msg = '登录成功' order by login_time desc) where rownum = 1");
        sql.setParam("loginName",loginName);
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(Record.class));
        List<Record> dataList=dao.execute(sql).getList(Record.class);
        if(dataList.size()==1){
            return dataList.get(0);
        }else{
            return null;
        }
    }

    public int deleteLogininforByIds(Long[] infoIds){
        int result = dao.clear("sys_logininfor", Cnd.where("id","in",infoIds));
        return result;
    }

    public int cleanLogininfor(){
        int result = dao.clear("sys_logininfor");
        return result;
    }

}
